package com.demo.rxjavademo.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.demo.rxjavademo.R;
import com.demo.rxjavademo.adapter.GroupSectionAdapter;
import com.demo.rxjavademo.http.Http;
import com.demo.rxjavademo.loader.FrescoImageLoader;
import com.demo.rxjavademo.mode.BeforeNewsInfo;
import com.demo.rxjavademo.mode.GroupSection;
import com.demo.rxjavademo.mode.LastNewsInfo;
import com.demo.rxjavademo.mode.StoriesBean;
import com.demo.rxjavademo.utils.DateUtils;
import com.orhanobut.logger.Logger;
import com.xuj.banner.Banner;
import com.xuj.banner.BannerConfig;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private final String TAG = getClass().getSimpleName();
    private static final int TOTAL_COUNTER = 18;
    private int PAGE_SIZE;
    private int delayMillis = 1000;
    private int mCurrentCounter = 0;
    private boolean isErr;
    private boolean mLoadMoreEndGone = false;
    private Banner mBanner;
    private Toolbar toolbar;
    private RecyclerView mRecyclerView;
    //    private MainAdapter mMainAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private View mHeaderView;
    private Context mContext;
    private String date;
    private GroupSectionAdapter mGroupSectionAdapter;
    private List<StoriesBean> mNewsInfos = null;
    private List<GroupSection> mGroupSections = null;
    private List<LastNewsInfo.TopStoriesBean> mTopStoriesBeanList = null;
    Subscriber<LastNewsInfo> mNewsInfoSubscriber = new Subscriber<LastNewsInfo>() {
        @Override
        public void onSubscribe(Subscription s) {

            Logger.e(TAG, "onSubscribe");
            s.request(Long.MAX_VALUE);
            //通常在这儿请求资源，参数就是要请求的数量
        }

        @Override
        public void onNext(LastNewsInfo lastNewsInfo) {
            Logger.e(TAG, "onNext");

            mNewsInfos = lastNewsInfo.getStories();
            date = lastNewsInfo.getDate();
            String group = DateUtils.FriendlyDate(lastNewsInfo.getDate());
            mGroupSections.add(new GroupSection(true, group));
            for (int j = 0; j < mNewsInfos.size(); j++) {
                mGroupSections.add(new GroupSection(mNewsInfos.get(j)));
            }

            Logger.i(TAG, date);
            Logger.i(TAG, "size" + mGroupSections.size());

            mTopStoriesBeanList = lastNewsInfo.getTop_stories();
            List<String> mUrls = new ArrayList<>();
            for (int i = 0; i < mTopStoriesBeanList.size(); i++) {
                mUrls.add(mTopStoriesBeanList.get(i).getImage());
            }

            for (int i = 0; i < mUrls.size(); i++) {
                Logger.i(TAG, mUrls.get(i));
            }

            PAGE_SIZE = mNewsInfos.size();
            mBanner.setImages(mUrls)
                    .setImageLoader(new FrescoImageLoader());
            mGroupSectionAdapter.setNewData(mGroupSections);
            mGroupSectionAdapter.notifyDataSetChanged();
//            mMainAdapter.setNewData(mNewsInfos);
//            mMainAdapter.notifyDataSetChanged();

        }

        @Override
        public void onError(Throwable t) {
            Logger.e(TAG, "onError");

        }

        @Override
        public void onComplete() {
            Logger.e(TAG, "onComplete");
            mBanner.start();

        }
    };
    Subscriber<BeforeNewsInfo> mLoadMoreSubscriber = new Subscriber<BeforeNewsInfo>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(BeforeNewsInfo beforeNewsInfo) {

//            mMainAdapter.loadMoreComplete();
            mGroupSectionAdapter.loadMoreComplete();
            date = beforeNewsInfo.getDate();
            String group = DateUtils.FriendlyDate(beforeNewsInfo.getDate());
            List<GroupSection> mGroupList = new ArrayList<>();
            mGroupList.add(new GroupSection(true, group));

            List<StoriesBean> mList = beforeNewsInfo.getStories();
            for (int i = 0; i < mList.size(); i++) {
                Logger.d(TAG, mList.get(i).getTitle());
                mGroupList.add(new GroupSection(mList.get(i)));
            }
            mGroupSectionAdapter.addData(mGroupList);
            mGroupSectionAdapter.notifyDataSetChanged();
//            mMainAdapter.addData(mList);
//            mMainAdapter.notifyDataSetChanged();
        }


        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_home);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mGroupSections = new ArrayList<>();
        mContext = this;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mNewsInfos = new ArrayList<>();
        mTopStoriesBeanList = new ArrayList<>();
        initHeader();
        initAdapter();
        getData();
    }

    private void initBanner() {
        mBanner.isAutoPlay(true);
        mBanner.setDelayTime(3500);
        mBanner.setIndicatorGravity(BannerConfig.INDICATOR_CENTER);


    }

    private void initAdapter() {
        mGroupSectionAdapter = new GroupSectionAdapter(R.layout.item_home,
                R.layout.item_group_section,
                mGroupSections);

//        mMainAdapter = new MainAdapter(R.layout.item_home, mNewsInfos);
        if (mHeaderView != null) {
//            mMainAdapter.addHeaderView(mHeaderView);
            mGroupSectionAdapter.addHeaderView(mHeaderView);
        }
        mGroupSectionAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mGroupSectionAdapter.setOnLoadMoreListener(this);
//        mMainAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
//        mMainAdapter.setOnLoadMoreListener(this);
        mRecyclerView.setAdapter(mGroupSectionAdapter);
        mRecyclerView.setItemViewCacheSize(10 * 1024 * 1024);

    }

    private void initHeader() {
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        mHeaderView = mInflater.inflate(R.layout.home_header, null);
        mBanner = (Banner) mHeaderView.findViewById(R.id.banner);
        initBanner();
    }

    private void getData() {
        Http.getInstance().getLastNews(mNewsInfoSubscriber, "latest");
    }

    private void loadMore() {
        Http.getInstance().getBefore(mLoadMoreSubscriber, date);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mBanner.stopAutoPlay();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBanner.start();
    }

    @Override
    public void onRefresh() {

//        mMainAdapter.setEnableLoadMore(false);
        mGroupSectionAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                mMainAdapter.setNewData(DataServer.getSampleData(PAGE_SIZE));
                isErr = false;
                mCurrentCounter = PAGE_SIZE;
                mSwipeRefreshLayout.setRefreshing(false);
//                mMainAdapter.setEnableLoadMore(true);
                mGroupSectionAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);

    }


    @Override
    public void onLoadMoreRequested() {

        mRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {

                loadMore();
//                if (mCurrentCounter >= TOTAL_COUNTER) {
//                    //数据全部加载完毕
//                    mMainAdapter.loadMoreComplete();
//                } else {
//                    if (isErr) {
//                        //成功获取更多数据
////                                mMainAdapter.addData(DataServer.getSampleData(PAGE_SIZE));
////                                mCurrentCounter = mQuickAdapter.getData().size();
//
//
//                        mMainAdapter.loadMoreComplete();
//                    } else {
//                        //获取更多数据失败
//                        isErr = true;
//                        Toast.makeText(HomeActivity.this, R.string.network_err, Toast.LENGTH_LONG).show();
//                        mMainAdapter.loadMoreFail();
//
//                    }
//                }
            }

        }, delayMillis);

    }

    private void formatSession(String date) {
    }
}
